package com.tensquare.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description 网关过滤器
 * @Date 2021/4/5 19:36
 */
@Component
public class WebFilter extends ZuulFilter {

    /***
     * pre:操作之前执行
     * post：操作之后执行
     * Param: []
     **/
    @Override
    public String filterType() {
        return "pre";
    }

    /***
     * 多个执行顺序。数字越小优先级越高
     * Param: []
     **/
    @Override
    public int filterOrder() {
        return 0;
    }

    /***
     * 当前过滤器是否开启
     * Param: []
     **/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /***
     * 过滤器内执行的操作
     * return 任何值都表示放行
     * setSendZuulResponse(false) 表示不再继续执行
     * Param: []
     **/
    @Override
    public Object run() throws ZuulException {
        //做请求头的转发
        //得到request的上下文
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String header = request.getHeader("Authorization");
        if(null!=header && !"".equals(header)){
            //把头信息继续向下转发
            requestContext.addZuulRequestHeader("Authorization",header);
        }
        return null;
    }
}
